// 主应用文件 - 整合所有模块

import { loadConfig, showConfigModal, hideConfigModal, handleConfigSubmit } from './config.js';
import { analyzeStock, analyzeStocksBatch, fetchStocksWithSignals } from './analysis.js';
import { displayResult, displayBatchResults, showError, showProgress, updateProgress, saveAnalysisResult, shareAnalysisResult } from './resultHandler.js';
import { showModal, hideModal, initModalEvents } from './uiUtils.js';
import { initStockSuggestions } from './stockSuggestions.js';

// 信号股票列表的状态变量
let currentPage = 1;
let perPage = 20;
let currentSortBy = 'symbol';
let currentSortOrder = 'asc';

/**
 * 初始化应用
 */
async function initApp() {
    // 初始化模态框事件
    initModalEvents();
    
    // 加载配置
    try {
        await loadConfig();
    } catch (error) {
        console.error('加载配置失败:', error);
    }
    
    // 设置事件监听器
    setupEventListeners();
    
    // 初始化加载信号股票数据
    try {
        showSignalsLoading();
        await loadSignalsData();
    } catch (error) {
        showSignalsError(error.message);
        console.error('初始化信号股票失败:', error);
    }
}

/**
 * 加载信号股票数据
 */
async function loadSignalsData() {
    try {
        showSignalsLoading();
        const result = await fetchStocksWithSignals(currentPage, perPage, currentSortBy, currentSortOrder);
        displayStocksWithSignals(result.stocks, result.pagination);
    } catch (error) {
        showSignalsError(error.message);
        console.error('加载信号股票数据失败:', error);
    }
}

/**
 * 显示信号股票列表
 */
function displayStocksWithSignals(stocks, pagination) {
    const tableBody = document.getElementById('signalsTableBody');
    const signalsTable = document.getElementById('signalsTable');
    const noSignalsData = document.getElementById('noSignalsData');
    const signalsError = document.getElementById('signalsError');
    const signalsLoading = document.getElementById('signalsLoading');
    const paginationContainer = document.getElementById('signalsPagination');
    
    // 隐藏所有状态元素
    signalsLoading.classList.add('hidden');
    signalsError.classList.add('hidden');
    signalsTable.classList.add('hidden');
    noSignalsData.classList.add('hidden');
    paginationContainer.classList.add('hidden');
    
    if (!stocks || stocks.length === 0) {
        // 没有数据
        noSignalsData.classList.remove('hidden');
        return;
    }
    
    // 清空表格
    tableBody.innerHTML = '';
    
    // 填充表格数据
    stocks.forEach(stock => {
        const row = document.createElement('tr');
        row.className = 'bg-white border-b hover:bg-neutral-50';
        
        // 股票代码和名称
        row.innerHTML = `
            <td class="px-4 py-3">${stock.symbol}</td>
            <td class="px-4 py-3 font-medium">${stock.stock_name}</td>
            <td class="px-4 py-3">¥${stock.latest_price?.toFixed(2) || '-'}</td>
            <td class="px-4 py-3">
                ${stock.buy_signals && stock.buy_signals.length > 0 ? 
                    `<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                        <i class="fa fa-arrow-up mr-1"></i>${stock.buy_signals.length}
                    </span>` : '-'}
            </td>
            <td class="px-4 py-3">
                ${stock.sell_signals && stock.sell_signals.length > 0 ? 
                    `<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                        <i class="fa fa-arrow-down mr-1"></i>${stock.sell_signals.length}
                    </span>` : '-'}
            </td>
            <td class="px-4 py-3">
                <button class="view-details-btn bg-primary/10 text-primary px-3 py-1 rounded-md text-sm hover:bg-primary/20 transition" data-symbol="${stock.symbol}">
                    <i class="fa fa-eye mr-1"></i>查看详情
                </button>
            </td>
        `;
        
        tableBody.appendChild(row);
    });
    
    // 添加查看详情按钮事件
    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            const symbol = e.currentTarget.getAttribute('data-symbol');
            // 填充股票代码到输入框并触发分析
            document.getElementById('stockSymbol').value = symbol.split('.')[0]; // 只使用纯代码
            
            try {
                // 执行股票分析
                await analyzeStock(symbol.split('.')[0]);
                
                // 滚动到分析结果部分
                setTimeout(() => {
                    const resultContainer = document.getElementById('resultContainer');
                    if (resultContainer && !resultContainer.classList.contains('hidden')) {
                        resultContainer.scrollIntoView({ 
                            behavior: 'smooth', 
                            block: 'start' 
                        });
                    }
                }, 500); // 给分析结果一些渲染时间
            } catch (error) {
                console.error('分析股票失败:', error);
            }
        });
    });
    
    // 显示表格
    signalsTable.classList.remove('hidden');
    
    // 显示分页控件
    if (pagination && pagination.total_pages > 1) {
        renderPagination(pagination);
        paginationContainer.classList.remove('hidden');
    }
}

/**
 * 渲染分页控件
 */
function renderPagination(pagination) {
    const paginationContainer = document.getElementById('signalsPagination');
    paginationContainer.innerHTML = '';
    
    const { page, total_pages, total, per_page } = pagination;
    
    // 创建分页信息
    const paginationInfo = document.createElement('div');
    paginationInfo.className = 'flex items-center text-sm text-neutral-600 mr-4';
    paginationInfo.textContent = `显示 ${(page - 1) * per_page + 1} 到 ${Math.min(page * per_page, total)} 条，共 ${total} 条`;
    paginationContainer.appendChild(paginationInfo);
    
    // 创建分页按钮容器
    const paginationButtons = document.createElement('div');
    paginationButtons.className = 'flex';
    paginationContainer.appendChild(paginationButtons);
    
    // 上一页按钮
    const prevButton = document.createElement('button');
    prevButton.className = `px-3 py-1 rounded-l-md border ${page === 1 ? 'bg-neutral-100 text-neutral-400 cursor-not-allowed' : 'bg-white hover:bg-neutral-50'} border-neutral-300`;
    prevButton.innerHTML = '<i class="fa fa-chevron-left"></i>';
    prevButton.disabled = page === 1;
    prevButton.addEventListener('click', () => {
        if (page > 1) {
            currentPage = page - 1;
            loadSignalsData();
        }
    });
    paginationButtons.appendChild(prevButton);
    
    // 页码按钮
    const pageRange = getPageRange(page, total_pages);
    pageRange.forEach(pageNum => {
        const pageButton = document.createElement('button');
        pageButton.className = `px-3 py-1 border-t border-b ${pageNum === page ? 'bg-primary text-white' : 'bg-white hover:bg-neutral-50 text-neutral-700'} border-neutral-300`;
        pageButton.textContent = pageNum;
        pageButton.addEventListener('click', () => {
            currentPage = pageNum;
            loadSignalsData();
        });
        paginationButtons.appendChild(pageButton);
    });
    
    // 下一页按钮
    const nextButton = document.createElement('button');
    nextButton.className = `px-3 py-1 rounded-r-md border ${page === total_pages ? 'bg-neutral-100 text-neutral-400 cursor-not-allowed' : 'bg-white hover:bg-neutral-50'} border-neutral-300`;
    nextButton.innerHTML = '<i class="fa fa-chevron-right"></i>';
    nextButton.disabled = page === total_pages;
    nextButton.addEventListener('click', () => {
        if (page < total_pages) {
            currentPage = page + 1;
            loadSignalsData();
        }
    });
    paginationButtons.appendChild(nextButton);
}

/**
 * 获取页码范围
 */
function getPageRange(current, total) {
    const range = [];
    const maxVisiblePages = 5;
    
    let startPage = Math.max(1, current - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(total, startPage + maxVisiblePages - 1);
    
    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        range.push(i);
    }
    
    return range;
}

/**
 * 处理表头点击排序
 */
function handleHeaderSort(column) {
    if (currentSortBy === column) {
        // 如果点击当前排序列，则切换排序方向
        currentSortOrder = currentSortOrder === 'asc' ? 'desc' : 'asc';
    } else {
        // 否则设置新的排序列，默认为升序
        currentSortBy = column;
        currentSortOrder = 'asc';
        currentPage = 1; // 重新排序时重置到第一页
    }
    
    // 更新表头显示
    updateSortIndicators();
    
    // 重新加载数据
    loadSignalsData();
}

/**
 * 更新排序指示器
 */
function updateSortIndicators() {
    const headers = document.querySelectorAll('#signalsTable th[data-sort]');
    headers.forEach(header => {
        const column = header.getAttribute('data-sort');
        if (column === currentSortBy) {
            header.innerHTML = `${header.textContent.trim()} <i class="fa fa-sort-${currentSortOrder === 'asc' ? 'asc' : 'desc'}"></i>`;
            header.classList.add('text-primary');
        } else {
            header.innerHTML = `${header.textContent.trim()} <i class="fa fa-sort"></i>`;
            header.classList.remove('text-primary');
        }
    });
}

/**
 * 显示信号股票加载状态
 */
function showSignalsLoading() {
    const signalsLoading = document.getElementById('signalsLoading');
    const signalsTable = document.getElementById('signalsTable');
    const noSignalsData = document.getElementById('noSignalsData');
    const signalsError = document.getElementById('signalsError');
    
    signalsLoading.classList.remove('hidden');
    signalsTable.classList.add('hidden');
    noSignalsData.classList.add('hidden');
    signalsError.classList.add('hidden');
}

/**
 * 显示信号股票错误
 */
function showSignalsError(errorMessage) {
    const signalsError = document.getElementById('signalsError');
    const signalsErrorMessage = document.getElementById('signalsErrorMessage');
    const signalsLoading = document.getElementById('signalsLoading');
    const signalsTable = document.getElementById('signalsTable');
    const noSignalsData = document.getElementById('noSignalsData');
    
    signalsErrorMessage.textContent = errorMessage || '获取信号股票失败';
    signalsError.classList.remove('hidden');
    signalsLoading.classList.add('hidden');
    signalsTable.classList.add('hidden');
    noSignalsData.classList.add('hidden');
}

/**
 * 设置所有事件监听器
 */
function setupEventListeners() {
    // 配置相关事件
    document.getElementById('configBtn').addEventListener('click', showConfigModal);
    document.getElementById('closeConfigBtn').addEventListener('click', hideConfigModal);
    document.getElementById('configForm').addEventListener('submit', handleConfigSubmit);
    
    // 初始化股票建议功能
    initStockSuggestions();
    
    // 刷新按钮事件
    document.getElementById('refreshSignalsBtn').addEventListener('click', () => {
        currentPage = 1;
        loadSignalsData();
    });
    
    // 为表头添加排序事件
    document.addEventListener('DOMContentLoaded', () => {
        // 在DOM加载完成后更新排序指示器
        updateSortIndicators();
        
        // 为可排序的表头添加点击事件
        document.querySelectorAll('#signalsTable th[data-sort]').forEach(header => {
            header.addEventListener('click', () => {
                const column = header.getAttribute('data-sort');
                handleHeaderSort(column);
            });
            // 添加鼠标悬停效果
            header.classList.add('cursor-pointer', 'hover:bg-neutral-200', 'transition-colors');
        });
    });
    
    // 分析事件
    document.getElementById('analyzeBtn').addEventListener('click', () => {
        const symbol = document.getElementById('stockSymbol').value;
        analyzeStock(symbol);
    });
    
    // 批量分析事件
    document.getElementById('batchAnalyzeBtn').addEventListener('click', analyzeStocksBatch);
    
    // 结果操作事件
    document.getElementById('saveResultBtn').addEventListener('click', () => {
        const symbol = document.getElementById('resultSymbol').textContent.split(' ')[0];
        saveAnalysisResult(symbol);
    });
    
    document.getElementById('shareResultBtn').addEventListener('click', shareAnalysisResult);
    
    // 信号股票相关事件
    document.getElementById('refreshSignalsBtn').addEventListener('click', () => {
        fetchStocksWithSignals().then(stocks => {
            displayStocksWithSignals(stocks);
        }).catch(error => {
            showSignalsError(error.message);
        });
    });
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);